package com.igeek.ch01.jdbc;

import com.igeek.pojo.User;

import java.sql.*;

/**
 * @package com.igeek.ch01.jdbc
 * @Description
 * @Author LittlePunk [296526219@qq.ccom]
 * @Version 2022.1
 * @Date 2023/11/18 11:28
 */
public class UserDao {
    public User selectOne(int id) throws ClassNotFoundException, SQLException {
        //1.注册驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
        //2.获取连接对象
        Connection connection =
                DriverManager.getConnection(
                        "jdbc:mysql://localhost:3306/igeekmybatis?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai",
                        "root",
                        "1234");
        //3.创建预编译语句对象
        PreparedStatement ps = connection.prepareStatement("select * from user where id=?");
        //4.给问号处赋值
        ps.setInt(1, id);
        //5.执行sql 后获取的结果集ResultSet
        ResultSet rs = ps.executeQuery();
        User user = null;
        while (rs.next()) {
            user = new User(
                    rs.getInt("id"),
                    rs.getString("name"),
                    rs.getString("gender"));

        }
        //6.释放连接资源
        if(rs!=null){
            rs.close();
        }
        if(ps!=null){
            ps.close();
        }
        if(connection!=null){
            connection.close();
        }
        return user;
    }

    public void test1(){
        System.out.println("test1");
    }
    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        UserDao userDao = new UserDao();
        User user = userDao.selectOne(1);
        System.out.println("user = " + user);
    }
}
